#include "GTimer.h"

Event GTimer::TIMER_EVENT("TICK");

GTimer::GTimer(void)
{
	updatePtr = new FatPointer <GTimer, void>(this, METHOD(void, GTimer, update));
}

GTimer::~GTimer(void)
{
	delete updatePtr;
}

void GTimer::setTimer(unsigned int _ms, unsigned int _repeatCount)
{
	CPF = Config::DELTA_TIME / _ms;
	ticks = 0;
	cyclesPassed = 0;
	repeatCount = _repeatCount;
	currentCount = 0;
}

void GTimer::start()
{
	Controller::getController()->addEventListaner(Controller::UPDATE_EVENT, updatePtr);
}

void GTimer::stop()
{
	Controller::getController()->removeEventListener(Controller::UPDATE_EVENT, updatePtr);
}

void GTimer::update(Event *e)
{
	cyclesPassed += CPF;
	ticks = floor(cyclesPassed);
	cyclesPassed -= ticks;
	for(i = 0; i < ticks; ++i)
	{
		dispatchEvent( &TIMER_EVENT );
		if(repeatCount != 0)
		{
			++currentCount;
			if(currentCount >= repeatCount)
			{
				stop();
				break;
			}
		}
	}
	ticks = 0;
}
